namespace ScrumSprintMonitor.Samples.Widgets
{
    #region #using Directives

    using System;
    using System.ComponentModel.Composition;

    using Extensibility;
    using Extensibility.Events;

    using Infrastructure;

    using Microsoft.Practices.Composite.Events;
    using Microsoft.Practices.Unity;

    #endregion

    [Export(typeof(ScrumSprintMonitorAddIn))]
    [AddIn(Name = "Widget Server")]
    public class WidgetServerAddIn : ScrumSprintMonitorAddIn
    {
        private WidgetServerService widgetServerService;

        #region Overrides of ScrumSprintMonitorAddIn

        public override void Load()
        {
            var eventAggregator = ServiceLocator.GetInstance<IEventAggregator>();
            eventAggregator.GetEvent<MonitorStartedEvent>().Subscribe(OnMonitorStarted);
        }

        public override void Unload()
        {
            if (this.widgetServerService != null)
            {
                this.widgetServerService.Dispose();
            }
        }

        #endregion

        private void OnMonitorStarted(EventArgs obj)
        {
            var reportableData = (IReportableData) ServiceLocator.GetInstance(typeof(IReportableData));

            this.widgetServerService = new WidgetServerService(reportableData, ServiceLocator.GetInstance<IUnityContainer>());
        }
    }
}